/**
 * Created by alice on 2017/5/15 0015.
 */
;-function ($, window, document, undefined) {
    "use strict";
    var isTouch = 'ontouchstart' in window,
        eStart = isTouch ? 'touchstart' : 'mousedown',
        eMove = isTouch ? 'touchmove' : 'mousemove',
        eEnd = isTouch ? 'touchend' : 'mouseup',
        eCancel = isTouch ? 'touchcancel' : 'mouseup',
        secondsToTime = function (secs) {
            var hours = Math.floor(secs / 3600), minutes = Math.floor(secs % 3600 / 60),
                seconds = Math.ceil(secs % 3600 % 60);
            return ( hours == 0 ? '' : hours > 0 && hours.toString().length < 2 ? '0' + hours + ':' : hours + ':' ) + ( minutes.toString().length < 2 ? '0' + minutes : minutes ) + ':' + ( seconds.toString().length < 2 ? '0' + seconds : seconds );
        };

    var cssClass = {},
        cssClassSub =
            {
                playPause: 'playpause',
                playing: 'playing',
                time: 'time',
                timeCurrent: 'time-current',
                timeDuration: 'time-duration',
                bar: 'bar',
                barLoaded: 'bar-loaded',
                barPlayed: 'bar-played',
                volume: 'volume',
                volumeButton: 'volume-button',
                volumeAdjust: 'volume-adjust',
                noVolume: 'novolume',
                mute: 'mute',
                mini: 'mini'
            };
    var thePlayer = null,
        theAudio = null,
        theBar = null,
        barPlayed = null,
        barLoaded = null,
        timeCurrent = null,
        timeDuration = null,
        volumeButton =null,
        volumeAdjuster =null,
        volumeDefault = 0,
        adjustCurrentTime=null,
        adjustVolume=null,
        updateLoadBar=null;
    //TODO 初始化的方法写这里面
    var init = function () {
        init_ready();//加载预设变量
        init_event();
        function init_event() {//TODO 初始化页面事件

        }

        function init_ready() {//TODO 初始化预设值

        }
    };
    //TODO 内部调用的方法写这里
    var Class = {
        audioPlayer: function (params) {
            params = $.extend({
                classPrefix: 'audioplayer',
                strPlay: 'Play',
                strPause: 'Pause',
                strVolume: 'Volume'
            }, params);
            for (var subName in cssClassSub) {
                cssClass[subName] = params.classPrefix + '-' + cssClassSub[subName];
            }

            var $this = $('audio');
            thePlayer = $('<div class="' + params.classPrefix + '">' +
                    $('<div>').append($this.clone()).html()),
                theAudio = thePlayer.find('audio');
            theAudio.duration = params.duration;
            console.log(theAudio.duration );

            thePlayer.find('audio').css({'width': 0, 'height': 0, 'visibility': 'hidden'});
            thePlayer.append('<div class="' + cssClass.time + ' ' + cssClass.timeCurrent + '"></div>' +
                '<div class="' + cssClass.bar + '"><div class="' + cssClass.barLoaded + '"></div>' +
                '<div class="' + cssClass.barPlayed + '"></div>' +
                '</div>' +
                '<div class="' + cssClass.time + ' ' + cssClass.timeDuration + '"></div>' +
                '<div class="' + cssClass.volume + '">' +
                '<div class="' + cssClass.volumeButton + '" title="' + params.strVolume + '">' +
                '<a href="#">' + params.strVolume + '</a>' +
                '</div>' +
                '<div class="' + cssClass.volumeAdjust + '"><div><div></div></div></div></div>');

            theBar = thePlayer.find('.' + cssClass.bar),
                barPlayed = thePlayer.find('.' + cssClass.barPlayed),
                barLoaded = thePlayer.find('.' + cssClass.barLoaded),
                timeCurrent = thePlayer.find('.' + cssClass.timeCurrent),
                timeDuration = thePlayer.find('.' + cssClass.timeDuration),
                volumeButton = thePlayer.find('.' + cssClass.volumeButton),
                volumeAdjuster = thePlayer.find('.' + cssClass.volumeAdjust + ' > div'),
                volumeDefault = 0,
                adjustCurrentTime = function (e) {
                    theAudio.currentTime = Math.round(( theAudio.duration * ( e.pageX - theBar.offset().left ) ) / theBar.width());
                },
                adjustVolume = function (e) {
                    theAudio.volume = Math.abs(( e.pageY - ( volumeAdjuster.offset().top + volumeAdjuster.height() ) ) / volumeAdjuster.height());
                }
                // updateLoadBar = setInterval(function () {
                //     barLoaded.width(( theAudio.buffered.end(0) / theAudio.duration ) * 100 + '%');
                //     if (theAudio.buffered.end(0) >= theAudio.duration)
                //         clearInterval(updateLoadBar);
                // }, 100);

            var volumeTestDefault = theAudio.volume, volumeTestValue = theAudio.volume = 0.111;
            if (Math.round(theAudio.volume * 1000) / 1000 == volumeTestValue) theAudio.volume = volumeTestDefault;
            else thePlayer.addClass(cssClass.noVolume);

            //修改显示总时间
            timeDuration.html(secondsToTime(params.duration));
            timeCurrent.text(secondsToTime(0));

            theAudio.addEventListener('loadeddata', function () {
                timeDuration.text(secondsToTime(theAudio.duration));
                volumeAdjuster.find('div').height(theAudio.volume * 100 + '%');
                volumeDefault = theAudio.volume;
            });

            theAudio.addEventListener('volumechange', function () {
                volumeAdjuster.find('div').height(theAudio.volume * 100 + '%');
                if (theAudio.volume > 0 && thePlayer.hasClass(cssClass.mute)) thePlayer.removeClass(cssClass.mute);
                if (theAudio.volume <= 0 && !thePlayer.hasClass(cssClass.mute)) thePlayer.addClass(cssClass.mute);
            });

            theAudio.addEventListener('ended', function () {
                thePlayer.removeClass(cssClass.playing);
            });

            theBar.on(eStart, function (e) {
                adjustCurrentTime(e);
                theBar.on(eMove, function (e) {
                    adjustCurrentTime(e);
                });
            })
                .on(eCancel, function () {
                    theBar.unbind(eMove);
                });

            volumeButton.on('click', function () {
                if (thePlayer.hasClass(cssClass.mute)) {
                    thePlayer.removeClass(cssClass.mute);
                    theAudio.volume = volumeDefault;
                }
                else {
                    thePlayer.addClass(cssClass.mute);
                    volumeDefault = theAudio.volume;
                    theAudio.volume = 0;
                }
                return false;
            });

            volumeAdjuster.on(eStart, function (e) {
                adjustVolume(e);
                volumeAdjuster.on(eMove, function (e) {
                    adjustVolume(e);
                });
            })
                .on(eCancel, function () {
                    volumeAdjuster.unbind(eMove);
                });

            thePlayer.find('.' + cssClass.playPause).on('click', function () {
                if (thePlayer.hasClass(cssClass.playing)) {
                    $(this).attr('title', params.strPlay).find('a').html(params.strPlay);
                    thePlayer.removeClass(cssClass.playing);
                }
                else {
                    $(this).attr('title', params.strPause).find('a').html(params.strPause);
                    thePlayer.addClass(cssClass.playing);
                }
                return false;
            });

            $this.replaceWith(thePlayer);

        },
        time_update:function (time) {
            timeCurrent.text(secondsToTime(time));
            barPlayed.width(( time / theAudio.duration ) * 100 + '%');
        }
    };
    init();
    //TODO 对外公开的方法写在这里
    window.audio = {
        audioPlayer:Class.audioPlayer,
        time_update:Class.time_update
    };
}(jQuery, window, document);
